/** @file    FormSystemMonitor.cpp
 *  @author  Alessandro Polo
 *  @version $Id: FormSystemMonitor.cpp 2867 2010-08-07 20:44:51Z alex $
 *  @brief
 * File containing methods for the wosh::gui::FormSystemMonitor class.
 * The header for this class can be found in FormSystemMonitor.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include "FormSystemMonitor.h"
 #include "ui_FormSystemMonitor.h"
 #include <core/SystemMonitor.h>

 #include <framework/gui/widgets/wCore_SystemError.h>

using namespace std;
namespace wosh {
 namespace gui {

 WOSH_REGISTER(wosh::gui::FormSystemMonitor, "wosh::gui::IWidgetGeneric", 1.0, _static_FormSystemMonitor )
 WOSH_GUI_MAP(wosh::gui::FormSystemMonitor, "wosh::SystemMonitor", 0.0, _static_Map_FormSystemMonitor )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

FormSystemMonitor::FormSystemMonitor(QWidget *parent)
	: IWidgetGeneric(parent) {
	this->m_ui = new Ui::FormSystemMonitor();
	this->m_ui->setupUi(this);

	IWidgetGeneric::setTargetURI(_SystemMonitor_URI);

	// tab Summary [0]

	// tab System-Information [1]
	this->sysInfoModel = new PropertiesListTableModel(NULL, this);
	this->m_ui->tableViewSysInfo->setModel(this->sysInfoModel);
	connect(this->m_ui->wUpBarSysInfo, SIGNAL(updateClicked()), this, SLOT(refreshSysInfo()));
	this->mapMethodButton(_SystemMonitor_METHOD_update_sysinfo, this->m_ui->btnSystemInfoUpdate);

	// tab SystemErrors [2]
	this->m_ui->tableViewSystemErrors->setResizeStretch(5);
	//this->m_ui->tableViewSystemErrors->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableViewSystemErrors, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableViewSystemErrors, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableBundlesContextMenuRequested(const QPoint&, const QModelIndex&)) );
	connect(this->m_ui->tableViewSystemErrors->getTableView(), SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(tableViewSystemErrors_doubleClicked(const QModelIndex&)));
	mapMethodButton(_SystemMonitor_METHOD_clear_errors, this->m_ui->btnSystemErrorsClear);
	mapMethodButton(_SystemMonitor_METHOD_save_errors, this->m_ui->btnSystemErrorsDumpTo);

	// tab Profiling [3]
	this->m_ui->tableViewProfiling->setMethodList(_SystemMonitor_METHOD_profiles);
	this->m_ui->tableViewProfiling->setResizeStretch(1);
	connect(this->m_ui->tableViewProfiling, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->cmbProfilingSelector, SIGNAL(activated(int)), this, SLOT(refreshProfiling()));

	// tab DSM [4]
	this->m_ui->tableViewDsmSpaces->setMethodList(_SystemMonitor_METHOD_dsm);
	this->m_ui->cmbDsmSelector->setModel(this->m_ui->tableViewDsmSpaces->getTableView()->getTableModel());
	this->m_ui->cmbDsmSelector->setModelColumn(0);
	connect(this->m_ui->tableViewDsmSpaces, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->cmbDsmSelector, SIGNAL(activated(int)), this, SLOT(refreshDSM()));


	// tab Deprecated [5]
	this->m_ui->tableViewDeprecated->setMethodList(_SystemMonitor_METHOD_deprecated);
	connect(this->m_ui->tableViewDeprecated, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );

 }

FormSystemMonitor::~FormSystemMonitor() {
	delete this->m_ui;
 }

void FormSystemMonitor::changeEvent(QEvent *e) {
	QWidget::changeEvent(e);
	if ( e->type() == QEvent::LanguageChange )
		this->m_ui->retranslateUi(this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSystemMonitor::refreshAll() {
	this->setWindowTitle( QString("System Monitor [%1]").arg(this->getTargetURI().getKernelName().c_str()) );
	refreshSummary();
	this->m_ui->tableViewSystemErrors->refreshData();
	refreshSysInfo();
	refreshProfiling();
	this->m_ui->tableViewDsmSpaces->refreshData();
	refreshDSM();
	this->m_ui->tableViewDeprecated->refreshData();
 }

void FormSystemMonitor::refreshSummary() {

 }

void FormSystemMonitor::refreshSysInfo() {
	executeRemoteMethod( _METHOD_GetProperties, new Variant("SysInfo_*") );
	this->m_ui->wUpBarSysInfo->sayRetrieving();
 }

void FormSystemMonitor::refreshProfiling() {
	QString context = this->m_ui->cmbProfilingSelector->currentText();
	executeRemoteMethod( _SystemMonitor_METHOD_profiles, new Variant(context.toLatin1().data()) );
	this->m_ui->tableViewProfiling->getUpdateBar()->sayRetrieving();
 }

void FormSystemMonitor::refreshDSM() {
	this->m_ui->tableViewDSM->getTableModel()->loadTable(NULL);
	if ( this->m_ui->cmbDsmSelector->currentText().isEmpty() )
		return;
	
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSystemMonitor::tableViewSystemErrors_doubleClicked( const QModelIndex& ) {
	Variant dataID = this->m_ui->tableViewSystemErrors->getCurrentItemAsVariantAtCol(0);
	executeRemoteMethod( _METHOD_Retrieve, dataID );
	this->m_ui->tableViewSystemErrors->getUpdateBar()->showMessage( tr("Retrieving SystemError #%1").arg(dataID.toInt64(0)) );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSystemMonitor::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() || !message.getContent()->isResponse() ) return;
	if ( !isMessageForMeOrFromTarget(message) ) return;
	const wosh::Response* response = message.getContent()->asResponse();

	if ( response->getMethod() == _METHOD_GetProperties ) {
		if ( !response->hasData() || !response->getData()->isKindOf<List>() ) return;
		sysInfoModel->loadProps( response->getData()->as<List>() );
		this->m_ui->wUpBarSysInfo->sayReady();
		this->m_ui->tableViewSysInfo->resizeColumnsToContents();
		this->m_ui->tableViewSysInfo->horizontalHeader()->setStretchLastSection(true);
		return;
	 }
	else if ( response->getMethod() == _SystemMonitor_METHOD_deprecated ) {
		this->m_ui->tabDeprecated->setEnabled( (response->getReturnValue()!=WRET_ERR_ILLEGAL_USE) );
	 }
	else if ( response->getMethod() == _SystemMonitor_METHOD_profiles ) {
		this->m_ui->tableViewProfiling->setEnabled( (response->getReturnValue()!=WRET_ERR_ILLEGAL_USE) );
	 }
	else if ( response->getMethod() == _SystemMonitor_METHOD_update_sysinfo ) {
		refreshSysInfo();
		return;
	 }

	this->m_ui->tableViewSystemErrors->evalResponse(response);
	this->m_ui->tableViewProfiling->evalResponse(response);
	this->m_ui->tableViewDeprecated->evalResponse(response);
	this->m_ui->tableViewDsmSpaces->evalResponse(response);

	if ( !URI::pregMatch( this->myURI, message.getDestination() ) )
		return;

	if ( response->getMethod() == _METHOD_Retrieve ) {
		if ( response->getData()->isKindOf<List>() ) {
			const List* errList = response->getData()->as<List>();
			List::ConstIterator it;
			for (it=errList->begin(); it!=errList->end(); ++it) {
				const SystemError* err = (*it)->as<SystemError>();
				if ( err == NULL ) continue;
				wCore_SystemError* sysErrGui = new wCore_SystemError();
				sysErrGui->loadObject(err);
				sysErrGui->setReadOnly(true);
				GuiUtilities::showWidget( sysErrGui );
			 }
		 }
		else if ( response->getData()->isKindOf<SystemError>() ) {
			const SystemError* err = response->getData()->as<SystemError>();
			if ( err == NULL ) return;
			wCore_SystemError* sysErrGui = new wCore_SystemError();
			sysErrGui->loadObject(err);
			sysErrGui->setReadOnly(true);
			GuiUtilities::showWidget( sysErrGui );
		 }
		return;
	 }
	else
		promptMethodResponse(message);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
